package com.hudson.namesrv.handler;


import com.hudson.codec.domain.RemotingCommand;
import com.hudson.common.enums.MessageTypeEnum;
import com.hudson.core.json.JSONUtil;
import com.hudson.namesrv.util.NettyUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/24 11:31
 **/
public class ProducerMessageHandler extends SimpleChannelInboundHandler<RemotingCommand> {
    private static final Logger logger = LoggerFactory.getLogger(ProducerMessageHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.debug("连接成功");
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RemotingCommand msg) throws Exception {
        logger.debug("NameSrv 收到消息:" + msg);
        if (support(msg.getType())) {
            NettyUtil.write(ctx.channel(), RemotingCommand.builder()
                    .type(MessageTypeEnum.GET_BROKER_INFO.getType())
                    .body(JSONUtil.toJson(BrokerMessageHandler.BROKER_ADDRESS).getBytes(StandardCharsets.UTF_8))
                    .build());

            logger.debug("Producer 正常获取到 Broker 地址");
        }

        ctx.fireChannelRead(msg);
    }

    public boolean support(String type) {
        return MessageTypeEnum.GET_BROKER_INFO.getType().equals(type);
    }
}